package com.soft.small.util.http;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * @author Administrator
 *
 */
public class HttpUtil {

	/**
	 * 将map形式的参数转换为string形式
	 * @param params
	 * @return
	 */
	public static String createHttpString(Map<String, String> params){
		try {
			StringBuilder sb = null;
			String result;
			if (!params.isEmpty()){
				sb = new StringBuilder();
				for (String key:params.keySet() ) {
					sb.append(key).append("=").append(params.get(key)).append("&");
				}
				if (sb.length() > 0){
					sb.setLength(sb.length()-1);
				}
				return sb.toString();
			}else {
				return null;
			}

		}catch (Exception e){
			return null;
		}
	}

	/**
	 * 处理https get/post请求
	 *
	 *
	 */
	private static String request(String reqUrl, String reqMethod, Map<String, String> headers, Object params) {
		PrintWriter out = null;
		InputStream is = null;
		HttpURLConnection huc;
		BufferedReader buffer = null;
		String result = null;
		StringBuilder sb;
		try {
			trustAllHosts();
			URL url = new URL(reqUrl);
			if (url.getProtocol().toLowerCase().equals("https")) {
				HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
				https.setHostnameVerifier(HV);
				huc = https;
			} else {
				huc = (HttpURLConnection) url.openConnection();
			}
			huc.setConnectTimeout(30000);
			// 设置请求属性
			if (headers!= null && !headers.isEmpty()){
				for (String key : headers.keySet()) {
					huc.setRequestProperty(key,headers.get(key));
				}
			}
			// 发送post请求必须设置
			huc.setDoOutput(true);
			huc.setDoInput(true);
			// 设置请求方法
			huc.setRequestMethod(reqMethod);
			// 如果请求参数非空，发送请求参数
			if (null != params) {
				String paramStr = null;
				if (params instanceof String){
					paramStr = (String) params;
				}
				if (params instanceof Map){
					paramStr = createHttpString((Map<String, String>) params);
				}
				out = new PrintWriter(huc.getOutputStream());
				out.write(paramStr);
				out.flush();
			}
			System.out.println("请求地址："+reqUrl+",请求参数："+params);
			is = huc.getInputStream();
			buffer = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
			sb = new StringBuilder();
			String line;
			while ((line = buffer.readLine())!= null){
				sb.append(line);
			}
			result = sb.toString();
		} catch (Exception e) {
			System.out.println("发送" + reqMethod + "请求异常！");
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (is != null){
					is.close();
				}
				if (buffer != null){
					buffer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String requestPost(String reqUrl, String params) {

		return  request(reqUrl,"POST",null,params);
	}

	public static String requestPost(String reqUrl, Map<String, String> headers, String params) {
		return  request(reqUrl,"POST",headers,params);
	}

	public static String requestPost(String reqUrl, Map<String, String> headers, Map<String ,String> params) {
		return  request(reqUrl,"POST",headers,params);
	}

	public static String requestGet(String reqUrl, Map<String, String> headers) {
		return request(reqUrl,"GET",headers,null);
	}

	public static String requestGet(String reqUrl, String params) {
		return request(reqUrl,"GET",null,params);
	}

	/**
	 * 创建一个信任管理器不验证证书
	 *
	 */
	private static void trustAllHosts() {
		TrustManager[] tm = new TrustManager[] { new X509TrustManager() {

			public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

			}

			public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

			}

			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[] {};
			}

		} };
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, tm, null);
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private final static HostnameVerifier HV = new HostnameVerifier() {

		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};
}
